﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Csla;
using Csla.Data;
using System.Data;
using System.Data.Common;
using Asah.SiteWorx.SiteMap;
using System.Configuration;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.ExceptionHandling;
using System.Threading;
using System.Web;

namespace Asah.SiteWorx
{
    /// <summary>
    /// The site object represents one website within 
    /// SiteWorx.  This object uses the singleton design
    /// pattern so that no more than one site object is
    /// instanciated. 
    /// </summary>
    [Serializable()]
    public class Site
    {

        #region Business Methods

        private Guid _applicationId;
        private string _applicationName;
        private string _theme;
        private LinkedList<PageInfo> _navigationMenu;
        private string _currentPageUrl;
        private PageInfo _currentPageInfo;
        private static Site _instance = new Site();

        /// <summary>
        /// The application id is a unique guid that is
        /// created for each client website application.
        /// </summary>
        public Guid ApplicationId
        {
            get
            {
                return _applicationId;
            }
        }

        /// <summary>
        /// The website's name.
        /// </summary>
        public string ApplicationName
        {
            get
            {
                return _applicationName;
            }
        }

        /// <summary>
        /// The website's theme.
        /// </summary>
        public string Theme
        {
            get
            {
                return _theme;
            }
        }

        /// <summary>
        /// This returns the public navigation menu for
        /// a site.
        /// </summary>
        public LinkedList<PageInfo> NavigationMenu
        {
            get
            {
                if (_navigationMenu == null)
                    _navigationMenu = SiteMap.NavigationMenu.GetPublicMenu();
                return _navigationMenu;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public PageInfo CurrentPage
        {
            get
            {
                if (HttpContext.Current.Request.Path.ToString() != _currentPageUrl || _currentPageInfo == null)
                    _currentPageInfo = PageList.GetPageInfo(System.Web.HttpContext.Current.Request.Path.ToString());

                _currentPageUrl = HttpContext.Current.Request.Path.ToString();
                return _currentPageInfo;
            }
        }

        /// <summary>
        /// The constructor gets site information from the database
        /// and fills out the properties on the site object.
        /// </summary>
        private Site()
        {
            _applicationName = ConfigurationManager.AppSettings["ApplicationName"].ToString();
            GetSiteCommand command;
            command = DataPortal.Execute<GetSiteCommand>(new GetSiteCommand(_applicationName));
            _applicationId = command.ApplicationId;
            _theme = command.Theme;
        }

        public void Refresh()
        {
            _instance = new Site();
        }

        /// <summary>
        /// The method applies the passed in theme to the
        /// site.
        /// </summary>
        /// <param name="theme"></param>
        public void ApplyTheme(string theme)
        {
            DataPortal.Execute<SetSiteThemeCommand>(new SetSiteThemeCommand(theme));

            // after applying the new theme we need to refresh the site object.
            Refresh();
        }

        /// <summary>
        /// Retrieves the html content that is contained for the 
        /// specified control.
        /// </summary>
        /// <param name="controlId"></param>
        /// <returns></returns>
        public string GetGlobalContent(string controlId)
        {
            return DataPortal.Execute<GetSiteGlobalContentCommand>(new GetSiteGlobalContentCommand(controlId)).HtmlContent;
        }

        /// <summary>
        /// Set's the html content for the specified control.
        /// </summary>
        /// <param name="controlId"></param>
        /// <param name="htmlContent"></param>
        public void SetGlobalContent(string controlId, string htmlContent)
        {
            DataPortal.Execute<SetSiteGlobalContentCommand>(new SetSiteGlobalContentCommand(controlId, htmlContent));
        }

        #endregion
        
        #region Factory Methods

        /// <summary>
        /// The factory method returns the instance of the
        /// site object.  This object uses the singleton design
        /// pattern.
        /// </summary>
        /// <returns></returns>
        public static Site GetSite()
        {
            return _instance;
        }

        #endregion

        #region GetSiteCommand

        /// <summary>
        /// This command object gets the site information from 
        /// the database.
        /// </summary>
        [Serializable()]
        private class GetSiteCommand : CommandBase
        {
            private string _applicationName;
            private Guid _applicationId;
            private string _theme = "Default";

            public Guid ApplicationId
            {
                get
                {
                    return _applicationId;
                }
            }

            public string Theme
            {
                get
                {
                    return _theme;
                }
            }

            public GetSiteCommand(string applicationName)
            {
                _applicationName = applicationName;
            }

            protected override void DataPortal_Execute()
            {
                Database db = DatabaseFactory.CreateDatabase("SiteWorx");
                DbCommand dbCommand = db.GetStoredProcCommand("aspnet_Applications_CreateApplication");
                db.AddInParameter(dbCommand, "ApplicationName", DbType.String, _applicationName);
                db.AddOutParameter(dbCommand, "ApplicationId", DbType.Guid, 0);

                try
                {
                    db.ExecuteNonQuery(dbCommand);
                    _applicationId = (Guid)dbCommand.Parameters["@ApplicationId"].Value;
                }
                catch (Exception ex)
                {
                    bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Layer Policy");
                    if (rethrow)
                    {
                        throw;
                    }
                }
                
                // next get the site theme

                dbCommand = db.GetStoredProcCommand("aspnet_SiteTheme_GetTheme");
                db.AddInParameter(dbCommand, "ApplicationId", DbType.Guid, _applicationId);

                try
                {
                    using (var dr = new SafeDataReader(db.ExecuteReader(dbCommand)))
                    {
                        if (dr.Read())
                        {
                            _theme = dr.GetString("Theme");
                        }
                    }
                    dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Layer Policy");
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion

        #region SetSiteThemeCommand

        /// <summary>
        /// This command object updates the site
        /// theme in the database.
        /// </summary>
        [Serializable()]
        private class SetSiteThemeCommand : CommandBase
        {
            private string _theme;

            public SetSiteThemeCommand(string theme)
            {
                _theme = theme;
            }

            protected override void DataPortal_Execute()
            {
                Database db = DatabaseFactory.CreateDatabase("SiteWorx");
                DbCommand dbCommand = db.GetStoredProcCommand("aspnet_SiteTheme_SetTheme");
                db.AddInParameter(dbCommand, "ApplicationId", DbType.Guid, Site.GetSite().ApplicationId);
                db.AddInParameter(dbCommand, "Theme", DbType.String, _theme);
                db.AddInParameter(dbCommand, "LastUpdatedBy", DbType.Guid, Membership.User.GetUser(Thread.CurrentPrincipal.Identity.Name).ID);
                db.AddInParameter(dbCommand, "LastUpdatedDate", DbType.DateTime, DateTime.Now);

                try
                {
                    db.ExecuteNonQuery(dbCommand);
                    dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Layer Policy");
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion

        #region GetSiteGlobalContentCommand

        /// <summary>
        /// This command gets the html content from
        /// the specified control from the database.
        /// </summary>
        [Serializable()]
        private class GetSiteGlobalContentCommand : CommandBase
        {
            private string _controlId;
            private string _htmlContent = "";

            public string HtmlContent
            {
                get
                {
                    return _htmlContent;
                }
            }

           public GetSiteGlobalContentCommand(string controlId)
            {
                _controlId = controlId;
            }

            protected override void DataPortal_Execute()
            {
                Database db = DatabaseFactory.CreateDatabase("SiteWorx");
                DbCommand dbCommand = db.GetStoredProcCommand("aspnet_PersonalizationAllUsersGlobal_GetContent");
                db.AddInParameter(dbCommand, "ApplicationId", DbType.Guid, Site.GetSite().ApplicationId);
                db.AddInParameter(dbCommand, "ControlId", DbType.String, _controlId);

                try
                {
                    using (var dr = new SafeDataReader(db.ExecuteReader(dbCommand)))
                    {
                        if (dr.Read())
                        {
                            _htmlContent = dr.GetString("ControlContent");
                        }
                    }
                    dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Layer Policy");
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion

        #region SetSiteGlobalContentCommand

        /// <summary>
        /// This command object updates the html content for
        /// the specified control in the database.
        /// </summary>
        [Serializable()]
        private class SetSiteGlobalContentCommand : CommandBase
        {
            private string _controlId;
            private string _htmlContent;

            public SetSiteGlobalContentCommand(string controlId, string htmlContent)
            {
                _controlId = controlId;
                _htmlContent = htmlContent;
            }

            protected override void DataPortal_Execute()
            {
                Database db = DatabaseFactory.CreateDatabase("SiteWorx");
                DbCommand dbCommand = db.GetStoredProcCommand("aspnet_PersonalizationAllUsersGlobal_SetContent");
                db.AddInParameter(dbCommand, "ApplicationId", DbType.Guid, Site.GetSite().ApplicationId);
                db.AddInParameter(dbCommand, "ControlId", DbType.String, _controlId);
                db.AddInParameter(dbCommand, "ControlContent", DbType.String, _htmlContent);
                db.AddInParameter(dbCommand, "LastUpdatedBy", DbType.Guid, Membership.User.GetUser(Thread.CurrentPrincipal.Identity.Name).ID);
                db.AddInParameter(dbCommand, "LastUpdatedDate", DbType.DateTime, DateTime.Now);

                try
                {
                    db.ExecuteNonQuery(dbCommand);
                    dbCommand.Dispose();
                }
                catch (Exception ex)
                {
                    bool rethrow = ExceptionPolicy.HandleException(ex, "Data Access Layer Policy");
                    if (rethrow)
                    {
                        throw;
                    }
                }
            }
        }
        #endregion

    }
}
